<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { initRouter } from "@/router/utils";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount, computed } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

import { setToken } from "@/utils/auth";
import { usePermissionStoreHook } from "@/store/modules/permission";
import regist from "./components/regist.vue";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: ""
});
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});
//   改为纯静态路由

// const onLogin = async (formEl: FormInstance | undefined) => {
//   loading.value = true;
//   if (!formEl) return;
//   await formEl.validate((valid, fields) => {
//     if (valid) {
//       useUserStoreHook()
//         .loginByUsername({ username: ruleForm.username, password: "admin123" })
//         .then(res => {
//           if (res.success) {
//             // 获取后端路由
//             initRouter().then(() => {
//               router.push("/");
//               message("登录成功", { type: "success" });
//             });
//           }
//         });
//     } else {
//       loading.value = false;
//       return fields;
//     }
//   });
// };
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 全部采取静态路由模式
      usePermissionStoreHook().handleWholeMenus([]);

      useUserStoreHook()
        .loginByUsername({ phoneNub: ruleForm.username, password: ruleForm.password })
        .then(res => {
          if (res.code == 200) {
            console.log("登入成功==", res);
            setToken({
              username: res.data.username,
              roles: res.data.roles,
              userId: res.data.id,
              accessToken: "eyJhbGciOiJIUzUxMiJ9.admin",
              refreshToken: "eyJhbGciOiJIUzUxMiJ9.adminRefresh",
              expires: "2023/10/30 00:00:00"
            } as any);
            // 获取静态路由
            usePermissionStoreHook().handleWholeMenus([]);
            router.push("/");
            message("登录成功", { type: "success" });
          } else {
            message(res.message, { type: "error" });
            loading.value = false;
          }
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

// 去注册
function toRegist() {
  useUserStoreHook().SET_CURRENTPAGE(3);
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon" @change="dataThemeChange" />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <div v-if="currentPage === 0">
            <Motion :delay="50">
              <avatar class="avatar" />
              <h2 class="outline-none">{{ title }}</h2>
            </Motion>
          </div>
          <div v-if="currentPage === 3">
            <Motion :delay="50">
              <avatar class="avatar" />
              <h2 class="outline-none">{{ title }}</h2>
            </Motion>
          </div>

          <el-form v-if="currentPage === 0" ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入电话号码',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input clearable v-model="ruleForm.username" placeholder="电话号码" :prefix-icon="useRenderIcon(User)" />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="">
                <el-input clearable show-password v-model="ruleForm.password" placeholder="密码" :prefix-icon="useRenderIcon(Lock)" />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading" @click="onLogin(ruleFormRef)"> 登录 </el-button>
            </Motion>

            <Motion :delay="350">
              <el-button class="w-full mt-4" size="default" type="default" :loading="loading" @click="toRegist"> 注册 </el-button>
            </Motion>
          </el-form>

          <regist v-if="currentPage === 3" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
